<template>
  <div>
    <el-dialog
      :title="title"
      :visible="visible"
      width="50%"
      top="4vh"
      :close-on-click-modal="false"
      @close="resetForm"
    >
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="上级菜单" prop="parentId">
          <div class="menu-tree">
            <el-tree
              :data="parentMenuOptions"
              :check-on-click-node="false"
              ref="tree"
              show-checkbox
              :check-strictly="true"
              node-key="id"
              :props="defaultProps"
              :default-expanded-keys="defaultExpandedKeys"
              @check-change="treeNodeClick"
              empty-text="暂无数据"
            />
          </div>
        </el-form-item>
        <el-form-item label="菜单标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入菜单标题" clearable> </el-input>
        </el-form-item>
        <el-form-item label="菜单副标题" prop="subTitle">
          <el-input v-model="formData.subTitle" placeholder="请输入菜单副标题" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="图标类名">
          <el-input v-model="formData.iconUrl" placeholder="请输入图标类名" clearable> </el-input>
        </el-form-item>
        <el-form-item label="路由名称" prop="linkName">
          <el-input v-model="formData.linkName" placeholder="请输入路由名称" clearable> </el-input>
        </el-form-item>
        <el-form-item label="路由地址" prop="linkUrl">
          <el-input v-model="formData.linkUrl" placeholder="请输入路由地址" clearable> </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="formData.sort" placeholder="请输入排序" clearable> </el-input>
        </el-form-item>
        <el-form-item label="是否是菜单" prop="isMenu">
          <el-radio-group v-model="formData.isMenu">
            <el-radio v-for="(item, index) in MENU_STATUS" :key="index" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio v-for="(item, index) in STATUS" :key="index" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="resetForm"> 取消 </el-button>
        <el-button type="primary" :loading="loading" @click="handelConfirm"> 确定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { STATUS } from '@/enum'
import { MENU_STATUS } from '@/enum/setting'
import rules from '../add-menu-rules'
export default {
  components: {},
  props: {
    id: {
      type: [String, Number],
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      title: '新增菜单',
      formData: {
        parentId: '',
        title: '',
        subTitle: '',
        iconUrl: '',
        linkName: '',
        linkUrl: '',
        status: 1,
        isMenu: true,
        sort: 99
      },
      parentId: [],
      loading: false,
      parentMenuOptions: [],
      defaultExpandedKeys: [],
      selectList: [],
      defaultProps: {
        value: 'id',
        children: 'children',
        label: 'title'
      }
    }
  },
  computed: {
    STATUS() {
      return STATUS
    },
    MENU_STATUS() {
      return MENU_STATUS
    },
    rules() {
      return rules
    },
    visible: {
      get() {
        return this.dialogVisible
      },
      set(val) {
        this.$emit('update:dialogVisible', val)
      }
    }
  },
  watch: {
    selectList: {
      handler(val) {
        console.log(val)
        this.formData.parentId = val[0]
      },
      deep: true
    }
  },
  created() {
    this.getParentOptions()
    this.getDetail()
  },
  mounted() {},
  methods: {
    async getParentOptions() {
      const {
        data: { id, parentId, title, children }
      } = await this.$http.system.menu.getNavsSelect()
      this.parentMenuOptions = [{ id, parentId, title, children }]
    },
    // 新增
    async add() {
      const { status, msg } = await this.$http.system.menu.add(this.formData)
      if (status === 200) {
        this.$message.success('添加成功')
        this.$emit('update:dialogVisible', false)
        this.$emit('getList')
      } else {
        this.$message.error(msg)
      }
    },
    // 编辑
    async updated() {
      const { status, msg } = await this.$http.system.menu.update({
        ...this.formData,
        id: this.id
      })
      if (status === 200) {
        this.$message.success('编辑成功')
        this.$emit('update:dialogVisible', false)
        this.$emit('getList')
      } else {
        this.$message.error(msg)
      }
    },
    // 获取详情
    async getDetail() {
      if (!this.type) return
      this.title = '编辑菜单'
      const { data } = await this.$http.system.menu.getDetail(this.id)
      for (const key in this.formData) {
        this.formData[key] = data[key]
      }
      this.$refs.tree.setCheckedKeys([this.formData.parentId])
      this.defaultExpandedKeys = [this.formData.parentId]
    },
    treeNodeClick(data, checked) {
      const node = this.$refs.tree.getNode(data)
      const str = []
      function filterName(node) {
        if (node) {
          if (node.parent) {
            str.push(node.data.name)
            filterName(node.parent)
          }
        }
      }
      // 获取当前选择的id在数组中的索引
      const indexs = this.selectList.indexOf(data.id)
      // 如果不存在数组中，并且数组中已经有一个id并且checked为true的时候，代表不能再次选择。
      if (indexs < 0 && this.selectList.length === 1 && checked) {
        this.$message.error('只能选择一个区域！')
        // 设置已选择的节点为false 很重要
        this.$refs.tree.setChecked(data, false)
      } else if (this.selectList.length === 0 && checked) {
        // 发现数组为空 并且是已选择
        // 防止数组有值，首先清空，再push
        this.selectList = []
        this.selectList.push(data.id)
        filterName(node)
      } else if (indexs >= 0 && this.selectList.length === 1 && !checked) {
        // 再次直接进行赋值为空操作
        this.selectList = []
      }
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$emit('update:dialogVisible', false)
      this.$emit('update:type', '')
    },
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.loading = true
        if (this.type === 'update') {
          this.updated()
        } else {
          this.add()
        }
        this.loading = false
        this.$emit('update:type', '')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.menu-tree {
  max-height: 400px;
  overflow-y: scroll;
}
.el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
    display: inline-block;
  }
  .el-checkbox .el-checkbox__inner {
    display: none;
  }
}
</style>
